/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.zyao89.view.zloading.slice;

import com.zyao89.view.zloading.ListItem;
import com.zyao89.view.zloading.ListProVider;
import com.zyao89.view.zloading.ResourceTable;
import com.zyao89.view.zloading.ZLoadingDialog;
import com.zyao89.view.zloading.Z_TYPE;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.ListContainer;
import ohos.agp.components.Text;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.agp.window.dialog.CommonDialog;
import ohos.global.configuration.DeviceCapability;
import ohos.global.resource.solidxml.TypedAttribute;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * 功能描述
 *
 * @author jjy
 * @since 2021-03-22
 */
public class MainAbilitySlice extends AbilitySlice implements Component.ClickedListener,
        ListContainer.ItemClickedListener {
    // 定义日志标签
    private static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP,
            0x00201, "zLoading MainAbilitySlice");
    private static final String LOADINGTYPE = "loading_type";
    private static final int TEXT_SIZE = 40;
    private static final int PARDING = 10;
    private static final double DURATIONTIME = 0.5;
    private static final int MARGIN = 50;
    private static final int MARGIN_TOP_BOTTOM = 5;
    private static final int CORNERRADIUS = 20;

    private Text leftText;
    private Button rightButton;
    private CommonDialog commonDialog;
    private int mSelectedItemIndex;
    private String bundleName;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        initView();
    }

    private void initView() {
        leftText = (Text)findComponentById(ResourceTable.Id_titleText);
        leftText.setText(ResourceTable.String_app_name);
        rightButton = (Button)findComponentById(ResourceTable.Id_rightButton);
        rightButton.setClickedListener(this::onClick);
        DirectionalLayout containerLinearLayout = (DirectionalLayout) findComponentById(ResourceTable.Id_container);
        createAllButton(containerLinearLayout);
        createButtons(containerLinearLayout);
        bundleName = getAbilityPackageContext().getBundleName();
    }

    @Override
    public void onClick(Component component) {
        commonDialog = new CommonDialog(this);
        Component listLayout = initListContainer();
        commonDialog.setSize(ComponentContainer.LayoutConfig.MATCH_CONTENT,
                ComponentContainer.LayoutConfig.MATCH_CONTENT);
        commonDialog.setContentCustomComponent(listLayout);
        commonDialog.setAutoClosable(true);
        commonDialog.show();
    }

    private Component initListContainer() {
        Component component = LayoutScatter.getInstance(getContext()).parse(ResourceTable.Layout_dialog_list,
                null, true);
        ListContainer listContainer = (ListContainer)component.findComponentById(
                ResourceTable.Id_dialog_list_container);
        listContainer.setItemClickedListener(this::onItemClicked);
        List<ListItem> list = getData();
        ListProVider sampleItemProvider = new ListProVider(list, this);
        listContainer.setItemProvider(sampleItemProvider);
        return component;
    }

    private ArrayList<ListItem> getData() {
        ArrayList<ListItem> list = new ArrayList<>();
        list.add(new ListItem("切换为dialog"));
        list.add(new ListItem("切换成新页面"));
        return list;
    }

    private void createAllButton(DirectionalLayout containerLinearLayout) {
        Button button = new Button(this);
        DeviceCapability deviceCapability = new DeviceCapability();
        deviceCapability.screenDensity = this.getResourceManager().getDeviceCapability().screenDensity;
        deviceCapability.deviceType = DeviceCapability.DEVICE_TYPE_PHONE;
        int padding = (int) TypedAttribute.computeTranslateRatio(deviceCapability) * PARDING;
        button.setPadding(padding, padding, padding, padding);
        containerLinearLayout.addComponent(button);
        button.setText("Show Time");
        ShapeElement element = new ShapeElement();
        element.setRgbColor(RgbColor.fromArgbInt(Color.GRAY.getValue()));
        element.setCornerRadius(CORNERRADIUS);
        button.setBackground(element);
        button.setLayoutConfig(new DirectionalLayout.LayoutConfig(DirectionalLayout.LayoutConfig.MATCH_PARENT,
                DirectionalLayout.LayoutConfig.MATCH_CONTENT));
        button.setMarginLeft(MARGIN);
        button.setMarginRight(MARGIN);
        button.setMarginTop(MARGIN_TOP_BOTTOM);
        button.setMarginBottom(MARGIN_TOP_BOTTOM);
        button.setTextSize(TEXT_SIZE);
        button.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                Intent intent = new Intent();
                Operation operation = new Intent.OperationBuilder()
                        .withDeviceId("")
                        .withBundleName(bundleName)
                        .withAbilityName("com.zyao89.view.zloading.ShowTimeAllAbility")
                        .build();
                intent.setOperation(operation);
                startAbility(intent);
            }
        });
    }

    private void createButtons(DirectionalLayout containerLinearLayout) {
        Z_TYPE[] types = Z_TYPE.values();
        for (Z_TYPE type : types) {
            Button button = new Button(this);
            DeviceCapability deviceCapability = new DeviceCapability();
            deviceCapability.screenDensity = this.getResourceManager().getDeviceCapability().screenDensity;
            deviceCapability.deviceType = DeviceCapability.DEVICE_TYPE_PHONE;
            int padding = (int) TypedAttribute.computeTranslateRatio(deviceCapability) * PARDING;
            button.setPadding(padding, padding, padding, padding);
            containerLinearLayout.addComponent(button);
            button.setTextSize(TEXT_SIZE);
            button.setText(String.format(Locale.getDefault(), "【%d】%s LOADING", type.ordinal(), type.name()));
            ShapeElement element = new ShapeElement();
            element.setRgbColor(RgbColor.fromArgbInt(Color.GRAY.getValue()));
            element.setCornerRadius(CORNERRADIUS);
            button.setBackground(element);
            button.setLayoutConfig(new DirectionalLayout.LayoutConfig(DirectionalLayout.LayoutConfig.MATCH_PARENT,
                    DirectionalLayout.LayoutConfig.MATCH_CONTENT));
            button.setMarginLeft(MARGIN);
            button.setMarginRight(MARGIN);
            button.setMarginTop(MARGIN_TOP_BOTTOM);
            button.setMarginBottom(MARGIN_TOP_BOTTOM);
            setupListener(button, type);
        }
    }

    private void setupListener(Component view, final Z_TYPE type) {
        final int index = type.ordinal();
        view.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                switch (mSelectedItemIndex) {
                    case 0:
                        ZLoadingDialog dialog = new ZLoadingDialog(getContext());
                        dialog.setLoadingBuilder(type)
                                .setLoadingColor(Color.getIntColor("#ff5305"))
                                .setHintText("正在加载中...")
                                .setHintTextSize(TEXT_SIZE) // 设置字体大小
                                .setHintTextColor(Color.GRAY.getValue())
                                .setDurationTime(DURATIONTIME) // 设置动画时间百分比
                                .setDialogBackgroundColor(Color.getIntColor("#cc111111")) // 设置背景色
                                .show();
                        break;
                    case 1:
                        Intent intent = new Intent();
                        Operation operation = new Intent.OperationBuilder()
                                .withDeviceId("")
                                .withBundleName(bundleName)
                                .withAbilityName("com.zyao89.view.zloading.ShowAbility")
                                .build();
                        intent.setParam(LOADINGTYPE,index);
                        intent.setOperation(operation);
                        startAbility(intent);
                        break;
                    default:
                        break;
                }
            }
        });
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    public void onItemClicked(ListContainer listContainer, Component component, int index, long l) {
        commonDialog.destroy();
        mSelectedItemIndex = index;
    }
}
